package com.szy.douyou_gateway.web;

import com.szy.douyou_classification.dao.Classification;
import com.szy.douyou_classification.dao.ClassificationReq;
import com.szy.douyou_gateway.client.ClassificationClient;
import com.szy.douyou_gateway.config.AccountProfile;
import com.szy.douyou_gateway.config.ResultDTO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 分类controller
 * @author sunziyan
 * @date 2022/5/12
 */
@RestController
@RequestMapping("/classification")
public class ClassificationController {
    @Resource
    private ClassificationClient classificationClient;

    /**
     * 查询所有分类信息
     *
     * @return
     */
    @PostMapping("/queryAll")
    public ResultDTO queryAll(@RequestBody ClassificationReq classificationReq) {
        return classificationClient.queryAll(classificationReq);
    }

    /**
     * 根据主键id查询分类信息
     *
     * @param classificationId
     * @return
     */
    @GetMapping("/queryOne/{classificationId}")
    public ResultDTO<Classification> queryOne(@PathVariable("classificationId") Long classificationId) {
        return classificationClient.queryOne(classificationId);
    }


    /**
     * 更新或插入单条分类信息
     *
     * @param classification
     * @return
     */
    @PostMapping("/addOrUpdateOne")
    @RequiresAuthentication
    public ResultDTO<Boolean> addOrUpdateOne(@RequestBody Classification classification) {
        Subject subject = SecurityUtils.getSubject();
        AccountProfile principal = (AccountProfile) subject.getPrincipal();
        if (!principal.getUserRight().equals(1)) {
            return ResultDTO.fail("需要管理员权限");
        }
        if (classification.getClassificationId() != null) {
            return classificationClient.updateOne(classification);
        } else {
            return classificationClient.addOne(classification);
        }


    }

    /**
     * 删除该分类
     *
     * @param id
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/deleteOne/{id}")
    public ResultDTO<Integer> deleteOne(@PathVariable("id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        AccountProfile principal = (AccountProfile) subject.getPrincipal();
        if (!principal.getUserRight().equals(1)) {
            return ResultDTO.fail("需要管理员权限");
        }
        return classificationClient.deleteOne(id);
    }
}
